<?php
/**
 * Created by PhpStorm.
 * User: wanglong
 * Date: 2017/12/26
 * Time: 21:49
 */

namespace app\modules\web\controllers;


use app\common\services\UploadServices;
use app\modules\web\controllers\common\BaseController;

class UploadController extends BaseController
{
    private $allow_file_type=[
        "jpg","png","jpeg","gif"
    ];
    /**
     * 上传接口
     * bucket  avatar/brand/book
     */
    public function actionPic()
    {
        $bucket=trim($this->post("bucket",""));

        $callback="window.parent.upload";//子页面调用父页面的js  iframe

        if(!$_FILES || !isset($_FILES['pic'])){
            return "<script>{$callback}.error('请选择文件之后在提交~~')</script>";
        }

        $file_name=$_FILES['pic']['name'];
        $tmp_file_extend=explode(".",$file_name);

        if(!in_array(strtolower(end($tmp_file_extend)),$this->allow_file_type)){
            return "<script>{$callback}.error('请上传指定类型的文件,允许上传的文件类型有jpg,jpeg,png,gif等~~')</script>";
        }


        //上传图片业务逻辑

        $res=UploadServices::uploadByFile($file_name,$_FILES['pic']['tmp_name'],$bucket);
        if(!$res){
            return "<script>{$callback}.error('".UploadServices::getLastErrorMsg()."')</script>";
        }
        return "<script>{$callback}.success('{$res["path"]}')</script>";
    }

}